package com.mn.ble.c

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat


class SplashActivity : AppCompatActivity() {

    private val PERMISSIONS_REQUEST_CODE = 0x0010

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
    }

    private fun initView() {
        if (reqPermissions()) {
            Handler(Looper.getMainLooper()).postDelayed({
                goMainFlow()
            }, 500)
        }
    }

    private fun goMainFlow() {
        MainActivity.jump(this)
        finish()
    }


    private fun reqPermissions(): Boolean {
        var permissionAllGranted = true
        val requestPermissionList = arrayOf(
            Manifest.permission.BLUETOOTH,
            Manifest.permission.ACCESS_FINE_LOCATION,
        )

        for (permission in requestPermissionList) {
            if (ActivityCompat.checkSelfPermission(
                    this,
                    permission
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                permissionAllGranted = false
                break
            }
        }
        if (!permissionAllGranted) {
            ActivityCompat.requestPermissions(
                this,
                requestPermissionList,
                PERMISSIONS_REQUEST_CODE
            )
        }
        return permissionAllGranted
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode != PERMISSIONS_REQUEST_CODE) {
            return
        }
        if (grantResults.isNotEmpty()) {
            val deniedPermissionList: MutableList<String?> = ArrayList()
            for (i in grantResults.indices) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    deniedPermissionList.add(permissions[i])
                }
            }
            if (deniedPermissionList.isEmpty()) {
                goMainFlow()
            } else {
                Toast.makeText(this, "失败", Toast.LENGTH_SHORT).show()
                finish()
            }
        }
    }

}